package com.hantang.web.json.handlers;

import java.util.Date;

import org.apache.log4j.Logger;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;

import com.google.gson.Gson;
import com.hantang.web.dao.ArticleDao;
import com.hantang.web.data.ArticleData;
import com.hantang.web.json.ds.MetaData;
import com.hantang.web.json.res.StringRes;

public class AddArticleHandler extends AbstractHandler {

	private static Logger logger = Logger.getLogger(AddArticleHandler.class);
	@Override
	public String doService(Request req, Response resp) throws Exception {
		String username = req.getParameter("username");
		String category = req.getParameter("category");
		String title = req.getParameter("title");
		String keyWords = req.getParameter("keyWords");
		String content = req.getParameter("content");
		
		String sret = handleServlet(username, category, title, keyWords,content);
		
		return sret;
	}

	public static String handleServlet(String username, String category,
			String title, String keyWords, String content) {
		ArticleData adata = new ArticleData();
		adata.setAuthor(username);
		adata.setCategory(category);
		adata.setContent(content);
		adata.setKeyWords(keyWords);
		adata.setTitle(title);
		adata.setUpdateTime(new Date());
		adata.setPublishTime(null);
		adata.setRemarks("");
		
		boolean isOk = handle(adata);
		StringRes res = new StringRes();
		if(isOk){
			res.setData(adata.getId() + "");
			res.setMeta(new MetaData(MetaData.META_DATA_SUCCESS_CODE,"Succ"));
		}else{
			res.setMeta(new MetaData(MetaData.META_DATA_FAILED_CODE,"Failed"));
		}
		String sret = new Gson().toJson(res);
		return sret;
	}

	public static boolean handle(ArticleData data)
	{
		if(data == null){
			return false;
		}
		boolean isOk = false;
		
		ArticleDao dao = new ArticleDao();
		long id = dao.saveData(data);
		if(id != -1)
		{
			isOk = true;
			logger.info("handle, saveArticleData Succ! id:" + id);
		}else{
			logger.error("handle, saveArticleData Failed! data:" + data.toString());
		}
		return isOk;
	}
}
